﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyAlbum.Model;

namespace PersonalAlbum
{
    public class PostModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            PostEntry post = new PostEntry();
            post.Title = bindingContext.ValueProvider.GetValue("Title").AttemptedValue;
            post.UserName = bindingContext.ValueProvider.GetValue("Author").AttemptedValue;

            DateTime? dt = GetA<DateTime>(bindingContext, "DateCreated");
            if (dt == null)
            {
                dt = DateTime.Now;
            }
            post.DateCreated = dt.Value;
            bool? approved = GetA<bool>(bindingContext, "Approved");
            post.Approved = approved.GetValueOrDefault();

            post.Content = bindingContext.ValueProvider.GetValue("Content").AttemptedValue;

            var tags = bindingContext.ValueProvider.GetValue("Tags").AttemptedValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(a => new Tag()
            {
                Name = a
            });
            post.Tags = tags;

            ValueProviderResult valueResult;
            try
            {
                if ((valueResult = bindingContext.ValueProvider.GetValue("ID")) != null)
                {
                    post.ID = valueResult.AttemptedValue;
                }
            }
            catch { }
            return post;
        }
        private Nullable<T> GetA<T>(ModelBindingContext bindingContext, string key) where T : struct
        {
            if (String.IsNullOrEmpty(key)) return null;
            ValueProviderResult valueResult = null;
            //Try it with the prefix...  
            try
            {
                valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "." + key);
            }
            catch { }
            //Didn't work? Try without the prefix if needed...  
            if (valueResult == null && bindingContext.FallbackToEmptyPrefix == true)
            {
                try
                {
                    valueResult = bindingContext.ValueProvider.GetValue(key);
                }
                catch { }
            }
            if (valueResult == null)
            {
                return null;
            }
            return (Nullable<T>)valueResult.ConvertTo(typeof(T));
        }

    }
}
